package org.redpig.mimall.service.impl;

import org.redpig.mimall.dao.CategoryMapper;
import org.redpig.mimall.enums.ResponseEnum;
import org.redpig.mimall.pojo.Category;
import org.redpig.mimall.service.ICategoryService;
import org.redpig.mimall.vo.CategoryVo;
import org.redpig.mimall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static org.redpig.mimall.consts.MimallConsts.ROOT_PARENT_ID;

@Service
public class CategoryServiceImpl implements ICategoryService {

    private final CategoryMapper categoryMapper;

    @Autowired
    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public ResponseVo<List<CategoryVo>> selectAll() {
        List<Category> categoryList = categoryMapper.selectAll();
        if (null == categoryList) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        if (categoryList.isEmpty()) {
            return ResponseVo.error(ResponseEnum.CATEGORY_ERROR);
        }

        //先查根目录
        /*for (Category category : categories) {
            if (ROOT_PARENT_ID.equals(category.getParentId())) {
                CategoryVo categoryVo = new CategoryVo();
                BeanUtils.copyProperties(category, categoryVo);
                categoryVoList.add(categoryVo);
            }
        }*/
        //lambda + stream 语法
        List<CategoryVo> categoryVoList = categoryList.stream()
                .filter(x -> x.getParentId().equals(ROOT_PARENT_ID))
                .map(this::category2CategoryVo)
                .sorted(Comparator.comparing(CategoryVo::getSortOrder).reversed())
                .collect(Collectors.toList());

        //查询子目录
        findSubCategory(categoryVoList, categoryList);

        return ResponseVo.success(categoryVoList);
    }

    private void findSubCategory(List<CategoryVo> categoryVoList, List<Category> categoryList) {
        for (CategoryVo categoryVo : categoryVoList) {

            List<CategoryVo> subCategoryList = new ArrayList<>();
            //查询整个数据库类目列表
            for (Category category : categoryList) {
                //如果查到，要设置子目录，还要继续往下查
                if (category.getParentId().equals(categoryVo.getId())) {
                    subCategoryList.add(category2CategoryVo(category));
                }
                findSubCategory(subCategoryList, categoryList);
            }
            subCategoryList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());
            categoryVo.setSubCategories(subCategoryList);
        }
    }

    private CategoryVo category2CategoryVo(Category category) {
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category, categoryVo);
        return categoryVo;
    }
}
